'use strict';

const Service = require('egg').Service;
const mailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const dayjs = require('dayjs');


class MailSvc extends Service {
  async sendMail(data) {
    const {config, logger} = this;

    // if (config.debug) {
    //   return;
    // }

    const transporter = mailer.createTransport(smtpTransport(config.mail_opts));

    for (let i = 1; i < 6; i++) {
      try {
        await transporter.sendMail(data);
        logger.info('send mail success', data);
        break;
      } catch (err) {
        if (i === 5) {
          logger.error('send mail finally error', err, data);
          throw new Error(err);
        }
        logger.error('send mail error', err, data);
      }
    }
  }

  async sendActiveMail(who, token, name) {
    const {config} = this;
    const from = `${config.name} <${config.mail_opts.auth.user}>`;
    const to = who;
    const subject = config.name + '社区帐号激活';
    const html = '<p>您好：' + name + '</p>' +
      '<p>我们收到您在' + config.name + '社区的注册信息，请点击下面的链接来激活帐户：</p>' +
      '<a href  = "' + config.host + '/active_account?key=' + token + '&name=' + name + '">激活链接</a>' +
      '<p>若您没有在' + config.name + '社区填写过注册信息，说明有人滥用了您的电子邮箱，请删除此邮件，我们对给您造成的打扰感到抱歉。</p>' +
      '<p>' + config.name + '社区 谨上。</p>';

    await this.sendMail({
      from,
      to,
      subject,
      html,
    });
  }


  async sendResetPassMail(who, token, name) {
    const {config} = this;
    const from = `${config.name} <${config.mail_opts.auth.user}>`;
    const to = who;
    const subject = config.name + '社区密码重置';
    const html = '<p>您好：' + name + '</p>' +
      '<p>我们收到您在' + config.name + '社区重置密码的请求，请在24小时内单击下面的链接来重置密码：</p>' +
      '<a href="' + config.host + '/reset_pass?key=' + token + '&name=' + name + '">重置密码链接</a>' +
      '<p>若您没有在' + config.name + '社区填写过注册信息，说明有人滥用了您的电子邮箱，请删除此邮件，我们对给您造成的打扰感到抱歉。</p>' +
      '<p>' + config.name + '社区 谨上。</p>';

    await this.sendMail({
      from,
      to,
      subject,
      html,
    });
  }


  async sendDeliveryMail(who, content) {
    const {ctx, config} = this;
    const from = `${config.name} <${config.mail_opts.auth.user}>`;
    const to = who;
    const subject = `淘沙快讯`;
    const time = dayjs().format('YYYY-MM-DD HH点');


    let html = `
<div style="width:100%;max-width:650px;margin: 0 auto;">
  <div style="font-family:Arial">
    <table
        style="border-collapse:collapse;border-left:1px solid #e4e4e4;border-right:1px solid #e4e4e4;width:100%;max-width:650px;margin: 0 auto;">
      <tbody>
      <tr>
        <td style="background-color:#f8f8f8;padding-left:7px;border-bottom:1px solid #e4e4e4;border-top:1px solid #e4e4e4"></td>
        <td valign="middle"
            style="padding:10px 0px;background-color:#f8f8f8;border-top:1px solid #e4e4e4;border-bottom:1px solid #e4e4e4">
          <a href="#" style="text-decoration:none; font-size: 22px;color: #222;" target="_blank">淘沙快讯</a>
          <span style="float: right;margin-top: 5px;">${time}</span>
        </td>
        <td style="background-color:#f8f8f8;padding-left:5px;border-top:1px solid #e4e4e4;border-bottom:1px solid #e4e4e4"></td>
      </tr>
      </tbody>
    </table>
`;

    for (let i = 0; i < content.length; i++) {
      const item = content[i];
      html += `<table style="border-collapse:collapse;border-left:1px solid #e4e4e4;border-right:1px solid #e4e4e4">
      <tbody>
      <tr>
        <td></td>
        <td style="padding:18px 0px 0px 0px;vertical-align:middle;line-height:20px;font-family:Arial;width: 100%;"><span
            style="color:#262626;font-size:20px">🆕 ${item.kw}</span>
        </td>
        <td></td>
      </tr>`;

      item.topics.forEach(v => {
        html += `<tr>
        <td style="padding-left:18px"></td>
        <td style="padding:18px 0px 12px 0px;vertical-align:top;font-family:Arial;border-bottom: 1px solid #e4e4e4;width: 100%;">
          <a></a>
          <div>
            <span style="padding:0px 6px 0px 0px">
            <a href="${v.original_url}" style="color:#427fed;display:inline;text-decoration:none;font-size:16px;line-height:20px"
               target="_blank">
            <span>${v.title}</span>
            </a>
            </span>
            <div>
              <div style="padding:2px 0px 8px 0px">
                <div style="color:#737373;font-size:12px"><a style="text-decoration:none;color:#737373">
                  <span>${v.author_name}</span> </a></div>
                <div
                    style="color:#252525;padding:2px 0px 0px 0px;font-size:12px;line-height:18px;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;-webkit-box-orient: vertical;-webkit-line-clamp: 3;">
                  ${v.intro}
                </div>
              </div>
            </div>
          </div>
        </td>
        <td style="padding-right:18px"></td>
      </tr>`
      });

      html += `<tr>
        <td colspan="3" valign="middle"
            style="background-color:#f8f8f8;font-size:14px;vertical-align:middle;text-align:center;padding:10px 10px 10px 10px;line-height:20px;border:1px solid #e4e4e4;font-family:Arial">
          <a href="https://taosha.club/search?q=${item.kw}" style="text-decoration:none;vertical-align:middle;color:#427fed" target="_blank">
            查看更多结果 </a>
        </td>
      </tr>
      </tbody>
    </table>`;
    }

    html += `<table style="padding-top:6px;font-size:12px;color:#252525;text-align:center;width:100%">
      <tbody>
      <tr>
        <td style="font-family:Arial"> 您收到此电子邮件是因为您订阅了<b>淘沙快讯</b>。
          <div>
            <a href="https://taosha.club/alert" style="text-decoration:none;color:#427fed" target="_blank">查看您所有的快讯 </a>
          </div>
        </td>
      </tr>
      </tbody>
    </table>
  </div>
</div>`;

    html = html.trim();


    await this.sendMail({
      from,
      to,
      subject,
      html,
    });
  }


}

module.exports = MailSvc;

